package com.xh.shuati.ai;
import com.xh.shuati.ai.tools.*;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.service.AiServices;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;

@Configuration
public class AiServiceConfig {

    @Resource
    private ChatLanguageModel myQwenChatModel;

    @Resource
    private StreamingChatLanguageModel myQwenStreamingChatModel;

    @Resource
    private ContentRetriever myContentRetriever;

    @Resource
    private McpToolProvider mcpToolProvider;

    @Resource
    private ChatMemoryProvider mySqlBasedChatMemoryProvder;


    @Bean
    public AiService aiService() {

        // 内存会话记忆
//        ChatMemory chatMemory = MessageWindowChatMemory.withMaxMessages(10);

//        会话记忆操作示例
//        ChatMemory chatMemory = chatMemoryProvider.get(1L);
//        chatMemory.add(new SystemMessage("给用户回答java问题"));
//        chatMemory = chatMemoryProvider.get(2L);
//        chatMemory.add(new UserMessage("我想知道为什么会这样"));

        // 构造 AI Service
        AiService aiService = AiServices.builder(AiService.class)
                .chatLanguageModel(myQwenChatModel)
                .streamingChatLanguageModel(myQwenStreamingChatModel)
                // 内存会话记忆，每个会话独立存储
//                .chatMemory(chatMemory)
//                .chatMemoryProvider(memoryId ->
//                        MessageWindowChatMemory.withMaxMessages(10))
                .chatMemoryProvider(mySqlBasedChatMemoryProvder)
                //开启RAG 检索增强生成
//                .contentRetriever(myContentRetriever)
                .toolProvider(mcpToolProvider)//mcp服务
                .tools(new InterviewQuestionTool(), new FileOperationTool(), new ResourceDownloadTool(), new WebScrapingTool(), new TerminalOperationTool(), new PDFGenerationTool()) // 工具调用
                .build();
        return aiService;
    }
}
